#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pthread.h>
#include <mqueue.h>

void *thread1(void *arg)
{
	mqd_t mq;
	struct mq_attr attr;
	char *msg = "message queue test";
	uint32_t msg_lenght = strlen(msg);
	
	//创建、打开信息队列
	attr.mq_flags = 0;
	attr.mq_maxmsg = 5;
	attr.mq_msgsize = 64;
	mq = mq_open("/test.mq", O_RDWR|O_CREAT, 0777, &attr);
	if(mq == (mqd_t) -1)
	{
		perror("mq_open:");
		return "mq_open failed";
	}
	while(1)
	{
		//发送信息
		if(mq_send(mq, msg, msg_lenght, 0) == -1)
		{
			perror("mq_send:");
			break;
		}
		sleep(1);
	}
	mq_close(mq);
	return "mq_send failed";
}

void *thread2(void *arg)
{
	mqd_t mq;
	struct mq_attr attr;
	char msg[64];
	uint32_t msg_lenght = sizeof(msg);
	
	//创建、打开信息队列
	attr.mq_flags = 0;
	attr.mq_maxmsg = 5;
	attr.mq_msgsize = 64;
	mq = mq_open("/test.mq", O_RDWR|O_CREAT, 0777, &attr);
	if(mq == (mqd_t) -1)
	{
		perror("mq_open:");
		return "mq_open failed";
	}
	while(1)
	{
		//接收消息
		if(mq_receive(mq, msg, msg_lenght, 0) == -1)
		{
			perror("mq_receive:");
			break;
		}
		printf("msg = %s\r\n", msg);
	}
	mq_close(mq);
	return "mq_receive failed";
}

int main(int argv, char *argc[])
{
	int restul;
	pthread_t tid1,tid2;

	//创建线程
	restul = pthread_create(&tid1, NULL, thread1, "this thread1");
	if(restul != 0)
	{
		printf("pthread_create: error code %d\r\n", restul);
		return -1;
	}
	restul = pthread_create(&tid2, NULL, thread2, "this thread2");
	if(restul != 0)
	{
		printf("pthread_create: error code %d\r\n", restul);
		return -1;
	}
	
	//主线程不能退出
	while(1)
	{
		sleep(10);
	}
}
